<template>
  <div class="table-box">
    <ProTable ref="proTable" title="项目列表" :columns="columns" :data="fetchedProjectList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic('新增')">新增项目</el-button>
        <el-button
          type="primary"
          :icon="DataAnalysis"
          plain
          @click="compareProjects(scope.selectedListIds)"
          :disabled="scope.selectedListIds.length < 2"
        >
          项目对比分析
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="openAnalysis(scope.row)">清单分析</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openResult(scope.row)">结果展示</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openBlockchain(scope.row)">区块链信息</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ProjectDrawer ref="drawerRef" @submit="handleSubmit" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { onMounted, ref } from "vue";
import { Project } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, DataAnalysis } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import ProjectDrawer from "@/views/proTable/components/projectDrawer.vue";
import { useRouter } from "vue-router";
import axios from "axios";

const router = useRouter();
/**实际使用的项目列表 */
const fetchedProjectList = ref<Partial<Project.ResProject>[]>([]);
/**当前用户 */
const userName = ref("");
/**当前表格实例 */
const proTable = ref<ProTableInstance>();
/**表格配置项 */
const columns: ColumnProps<Project.ResProject>[] = [
  { type: "selection", fixed: "left", width: 80 },
  {
    prop: "id",
    label: "项目编号",
    search: { el: "input" }
  },
  {
    // prop: "productId",
    prop: "productName",
    label: "产品名称",
    search: { el: "input" },
    width: 200
    // render: row => {
    //   // 根据 productId 查找产品名称
    //   const product = fetchedProductList.value.find(item => item.id === row.row.productId);
    //   return product ? product.productName || "产品名显示异常" : "未找到产品"; // 确保返回一个字符串
    // }
  },
  {
    prop: "projectStart",
    label: "计算起始时间",
    search: { el: "input" }
  },
  {
    prop: "projectEnd",
    label: "计算结束时间",
    search: { el: "input" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
];
const baseUrl = import.meta.env.VITE_BASE_URL;
onMounted(async () => {
  await initFormData();
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  if (userInfo.userName) {
    userName.value = userInfo.userName;
  }
});

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.post(baseUrl + "/api/carbon/getProjectList", {
      userId: userId
    });
    if (response.data && response.data.code === 200) {
      fetchedProjectList.value = response.data.data;
      console.log("响应数据_读取设备列表:", fetchedProjectList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取设备列表失败";
      console.error("获取设备列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取设备列表出错:", error);
    ElMessage.error("获取设备列表失败，可能是因为参数错误或网络问题");
  }
};

/**进入项目编辑界面 */
const openAnalysis = async (row: Partial<Project.ResProject> = {}) => {
  console.log(row.id);
  let savedTxId = "";
  try {
    const response = await axios.get(`${baseUrl}/api/carbon/getTxId?projectId=${row.id}`);
    if (response.data && response.data.code === 200) {
      savedTxId = response.data.data.txId;
      console.log("获取到的txId:", savedTxId);
    } else {
      console.warn("获取txId失败：", response.data?.msg || "未知错误");
    }
  } catch (error) {
    console.error("请求txId出错：", error);
  }
  // 如果有保存的交易ID，尝试查询区块链信息
  if (savedTxId !== "") {
    ElMessage({
      type: "warning",
      message: "该项目已分析完毕，请直接查看结果!"
    });
    return;
  }
  router.push(`/lca/purposeScope/${row.id}`);
};

//删除静态数组
const deleteAccount = async (params: Project.ResProject) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning", // 使用字符串形式的类型
    draggable: true
  })
    .then(async () => {
      try {
        const response = await axios.post(baseUrl + "/api/carbon/deleteProject", {
          id: params.id
        });
        if (response.data && response.data.code === 200) {
          ElMessage({
            type: "success",
            message: "删除项目成功!"
          });
          await initFormData(); // 删除成功后刷新列表
        } else {
          ElMessage.error(response.data.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除项目出错:", error);
        ElMessage.error("删除项目失败，可能是因为参数错误或网络问题");
      }
    })
    .catch(() => {
      // 如果用户取消了操作，则不做任何处理
    });
};

/**项目新增/编辑界面 */
const drawerRef = ref<InstanceType<typeof ProjectDrawer> | null>(null);

/**查看界面 */
const openDrawerStatic = (title: string, row: Partial<Project.ResProject> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};

const openResult = (row: Partial<Project.ResProject> = {}) => {
  router.push(`/lca/interpretation/${row.id}`);
};

const openBlockchain = (row: Partial<Project.ResProject> = {}) => {
  router.push(`/lca/blockchain/${row.id}`);
};

// 添加项目对比分析功能
const compareProjects = (ids: string[]) => {
  if (ids.length < 2) {
    ElMessage({
      type: "warning",
      message: "请选择至少两个项目进行对比分析!"
    });
    return;
  }
  // // 检查所有项目是否都已完成分析
  // const uncompletedProjects: string[] = [];

  // for (const id of ids) {
  //   const key = `processCarbonEmission_${id}`;
  //   const data = localStorage.getItem(key);

  //   if (!data) {
  //     const project = fetchedProjectList.value.find(item => item.id === id);
  //     const projectName = project ? fetchedProductList.value.find(p => p.id === project.productId)?.productName || id : id;
  //     uncompletedProjects.push(projectName);
  //   }
  // }

  // // 如果有未完成分析的项目，显示提示消息
  // if (uncompletedProjects.length > 0) {
  //   ElMessage({
  //     type: "error",
  //     message: `无法进行对比分析：以下项目未完成分析：${uncompletedProjects.join(", ")}`
  //   });
  //   return;
  // }

  // 将所有项目ID以逗号分隔，作为查询参数传递
  const projectIdsParam = ids.join(",");

  // 导航到对比分析页面
  router.push({
    path: "/lca/projectCompare",
    query: { projectIds: projectIdsParam }
  });

  // 记录日志
  console.log(
    "对比项目:",
    ids.map(id => fetchedProjectList.value.find(item => item.id === id))
  );
};
const handleSubmit = async () => {
  await initFormData();
};
</script>
